 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	/**
 * Enter description here ...
 * @author josue
 *
 * tags
 */
 
class Dispatcher extends CI_Controller{
	
	function Dispatcher(){
		parent::__construct();
		$this->load->helper("url");
		if($this->session->userdata('logged_in') == TRUE){
			$this->load->helpers(array('form','asset','url','html','language','file'));
			$this->load->library('form_validation');
			
			//esto variará dependiendo del lenguaje seleccionado por el usuario
			$this->lang->load("plot_layout",$this->session->userdata('language'));
			$this->lang->load("form_validation",$this->session->userdata('language'));
			
			$this->form_validation->set_rules("date","lang:date","required");
			$this->form_validation->set_rules("time","lang:time","required");
			$this->form_validation->set_rules("cuantosDias","lang:cuantosDias","required|integer|greater_than[1]|less_than[91]");
			$this->lang->load("plot_layout",$this->session->userdata('language'));
			
			
			$this->load->model('dbclient_model','dbclient');
			
		}else{
			$this->session->set_flashdata('errorMessage',$lang['error_no_login']);
			redirect('/');
		}
		
		
	}
	
	
	public function index(){
		
		echo "hola mundo";
		echo "\n" . $this->session->userdata("username");
	}
	
	public function validateForm(){
		
		$response = array();
		
		if($this->form_validation->run() == FALSE){
			$response["code"]=0;
			$response["message"] = "Error en el formulario";
			$response["cuantosDias_error"] = form_error("cuantosDias");
			$response["date_error"] = form_error("date");
			$response["time_error"] = form_error("time");
			$jsonResponse = json_encode($response);
			echo $jsonResponse;
		}else{
			//enviamos la petición para obtener los datos de la gráfica
			$tipo_reporte = $this->input->post("tipo_reporte");
			$variable = $this->input->post("variable");
			$date = $this->input->post("date");
			$time = $this->input->post("time");
			$numDias = $this->input->post("cuantosDias");
			$response["code"] = 1;
			$response["graphs"] = $this->get_data($tipo_reporte,$variable,$date,$time,$numDias);
			$response["variable"] = $variable;
			$response["tipo_reporte"] = $tipo_reporte;
			//Averiguando la unidad de la variable
			if(preg_match_all("/^Voltage_*/",$variable, $matches) != 0){
				$response["unidad"] = "Volt";
				
			}elseif (preg_match_all("/^Current_*/",$variable, $matches) != 0){
				$response["unidad"] = "Amper";
			}elseif (preg_match_all("/^Temperature_*/",$variable, $matches) != 0) {
				$response["unidad"] = "°Centrigrados";
			}elseif (preg_match_all("/^Humidity_*/",$variable, $matches) != 0) {
				$response["unidad"] = "% HR";
			}elseif (preg_match_all("/^PSTemperature_*/",$variable, $matches) != 0) {
				$response["unidad"] = "°Centrigrados";
			}elseif (preg_match_all("/^Diesel_*/",$variable, $matches) != 0) {
				$response["unidad"] = "% ";
			}elseif (preg_match_all("/^DigitalInput_*/",$variable, $matches) != 0) {
				$response["unidad"] = "Valor";
			}elseif (preg_match_all("/^DigitalOutput_*/",$variable, $matches) != 0) {
				$response["unidad"] = "Valor";
			}
			//Averiguando el formato de tiempo y tipo de reporte
			switch ($tipo_reporte) {
				case REPORTE_MULTIPLE:
					$response["tiempo"] = "Día";
					$response["reporte_title"] = "Reporte intervalo tiempo: ".$variable . "  a partir de " . $date;
				break;
				case REPORTE_POR_DIA:
					$response["tiempo"] = "hr:min";
					$response["reporte_title"] = "Reporte para un dia: ".$variable ." en ".$date." , ".$time;
				break;
				case REPORTE_POR_HORA:
					$response["tiempo"] = "hr:min";
					$response["reporte_title"] = "Reporte por hora : ".$variable ." en ".$date." , ".$time;
				break;
				default:
		
			}
			
			
			
			$jsonResponse = json_encode($response);
			echo $jsonResponse;
		}
	
	}
	public function plotLayout(){
		
		//$this->session->set_userdata("current_page",$this->uri->uri_string());
		$data['dbname'] = $this->session->userdata('dbname'); 
		$data['dbpassword'] = $this->session->userdata('dbpassword');
		$this->load->view("ploter_layout",$data);
		$this->load->view("footer");
			
	}
	
	public function showCalendar(){
		
		$data['month_names'] = $this->config->item('month_names');
		$data['day_names'] = $this->config->item('day_names');
		$data['allow_past'] = $this->config->item('allow_past');
		$data['date_format'] = $this->config->item('date_format');
		$this->load->view('calendar',$data);
		
	}
	
	

	public function get_data($tipo_reporte,$variable,$date,$time,$numDias){
		$resultSet = $this->dbclient->get_data($tipo_reporte,$variable,$date,$time,$numDias);
		return $this->_report_to_json($resultSet, $variable);
	}
	
	// public function get_interval_android($variable,$year,$month,$date,$numDias){
// 		
		// $query = "Select Date_Format(tkm_log.fecha, '%Y-%m-%d') AS fecha, ROUND(Avg(tkm_log.$variable), 2) As average 
// From tkm_log, (Select Date_Format(Concat(tkm_year.tkyears, '-', tkm_month.tkmonths, '-', tkm_day.tkdays), '%y-%m-%d') As fechaparametro From tkm_month, tkm_year, tkm_day Where tkm_year.tkyears = $year And tkm_month.tkmonths = $month And tkm_day.tkdays = $date) GetDateParameter,
 // (Select tkm_intervalo.tknumdays As numDias From tkm_intervalo Where tkm_intervalo.tknumdays = $numDias) getIntervalo 
// 
// Where tkm_log.fecha Between date_sub(Cast(GetDateParameter.fechaparametro As DateTime), Interval getIntervalo.numDias Day) AND Cast(GetDateParameter.fechaparametro As DateTime)
// Group By Date(tkm_log.fecha) 
// Order By tkm_log.fecha"; 
// 	
// // 		$resultSet = $this->db->query($query);
// 		
		// $Set = $this->dbclient->db->query($query);
		// $resultSet = $Set->result();
		// echo json_encode($resultSet);
	// }
	
	
	private function _report_to_json($resultSet,$variable){
	
		$result_array = array();
		$maximoValor = 0;
		$minimoValor = 10000;
			
		//for voltaje formats
		if(preg_match_all("/^Voltage_*|^Current_*/",$variable, $matches) != 0){
			$promedioA = array();
			$promedioB = array();
			$promedioC = array();
			$maximoA = array();
			$maximoB = array();
			$maximoC = array();
			$minimoA = array();
			$minimoB = array();
			$minimoC = array();
			foreach($resultSet as $result){
				$promedioA[] = array("x"=>$result->Fecha,"y"=>$result->Promedio_A);
									
				$promedioB[] = array("x"=>$result->Fecha,"y"=>$result->Promedio_B);
									
				$promedioC[] = array("x"=>$result->Fecha,"y"=>$result->Promedio_C);
				
				$maximoA[] = array("x"=>$result->Fecha,"y"=>$result->Maximo_A);
				
				if($maximoValor < $result->Maximo_A)
					$maximoValor = $result->Maximo_A;
				
				$maximoB[] = array("x"=>$result->Fecha,"y"=>$result->Maximo_B);
				if($maximoValor < $result->Maximo_B)
					$maximoValor = $result->Maximo_B;
				
				$maximoC[] = array("x"=>$result->Fecha,"y"=>$result->Maximo_C);
				if($maximoValor < $result->Maximo_C)
					$maximoValor = $result->Maximo_C;
				
				$minimoA[] = array("x"=>$result->Fecha,"y"=>$result->Minimo_A);
				
				if($minimoValor > $result->Minimo_A)
					$minimoValor = $result->Minimo_A;
				
				$minimoB[] = array("x"=>$result->Fecha,"y"=>$result->Minimo_B);
				
				if($minimoValor > $result->Minimo_B)
					$minimoValor = $result->Minimo_B;
				$minimoC[] = array("x"=>$result->Fecha,"y"=>$result->Minimo_C);
				
				if($minimoValor > $result->Minimo_C)
					$minimoValor = $result->Minimo_C;
	
			}
			
			$result_array[0] = array("nombre"=>"Promedio A","xml"=>$promedioA);
			$result_array[1] = array("nombre"=>"Máxima A","xml"=>$maximoA);
			$result_array[2] = array("nombre"=>"Mínima A","xml"=>$minimoA);
			$result_array[3] = array("nombre"=>"Promedio B","xml"=>$promedioB);
			$result_array[4] = array("nombre"=>"Máxima B","xml"=>$maximoB);
			$result_array[5] = array("nombre"=>"Mínima B","xml"=>$minimoB);
			$result_array[6] = array("nombre"=>"Promedio C","xml"=>$promedioC);
			$result_array[7] = array("nombre"=>"Máxima C","xml"=>$maximoC);
			$result_array[8] = array("nombre"=>"Mínima C","xml"=>$minimoC);
			//vector extra de información
			$result_array[9] = array("maximo"=>$maximoValor,"minimo"=>$minimoValor);
				
				
			/* if ( ! write_file("./assets/files/Promedio_A.xml", $promedioA)){
			 echo 'Unable to write the file';
			}else{
			echo 'File written!';
			} */
	
		}else{
			$promedio  = array();
			$maximo = array();
			$minimo = array();
			
			foreach($resultSet as $result){
	
				$promedio[] = array("x"=>$result->Fecha,"y"=>$result->Promedio);
				
				$maximo[] = array("x"=>$result->Fecha,"y"=>$result->Maxima);
				if($maximoValor < $result->Maxima)
					$maximoValor = $result->Maxima;
				
				$minimo[] = array("x"=>$result->Fecha,"y"=>$result->Minima);				
				if($minimoValor > $result->Minima)
					$minimoValor = $result->Minima;
			}
	
			$result_array[0] = array("nombre"=>"Promedio","xml"=>$promedio);
			$result_array[1] = array("nombre"=>"Máximo","xml"=>$maximo);
			$result_array[2] = array("nombre"=>"Mínimo","xml"=>$minimo);
			//Vector extra de información acerca de las gráficas
			$result_array[3] = array("maximo"=>$maximoValor,"minimo"=>$minimoValor);
				
		}
		return $result_array;
	
	}
	
	
	public function export(){
			
		$svgCode =  $this->input->post("svgCode");
		$data['graphic'] = $svgCode;
		$data['cliente'] = $this->session->userdata('username');
		$data['reporte_title'] = $this->input->post("reporte_title"); 
		$this->load->view('export_view',$data);
		$this->load->view("footer");
	}
	
}	
?>
